/*
 * OPIAM Suite
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */

package opiam.admin.applis.demo.servlets;

import org.apache.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.ByteArrayOutputStream;
import java.io.IOException;


/**
 * This servlet allows to download an orgchart file generated by the Views service.
 *<br>
 * HTTP PARAMETERS :<br>
 * <li>dn : entry dname</li>
 * <li>viewName  : view name</li>
 * <li>levelStr : number of levels</li>
 * <li>direction : orgchart type</li>
 * <li>mode : obsolete, should be 1</li>
 *<br>
 * WARNING : do not forget to configure the servlet in web.xml.
 */
public class GraphicOrgChartServlet extends HttpServlet
{
    /** Log4j logger. */
    private static Logger _logger =
        Logger.getLogger(GraphicOrgChartServlet.class);

    /**
     * Servlet processing method.
     * See HttpServlet.doGet
     *
     * @param request HTTP request
     * @param response HTTP response
     *
     * @throws java.io.IOException see HttpServlet
     * @throws javax.servlet.ServletException see HttpServlet
     */
    @Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
               throws IOException, ServletException
    {
        String typeimg = request.getParameter("type");
        _logger.debug("typeimg = " + typeimg);

        try
        {
            //Gets the session
            HttpSession session = request.getSession();

            ByteArrayOutputStream result =
                (ByteArrayOutputStream) session.getAttribute("IMG");
            byte[] byteArray = result.toByteArray();
            response.setContentType("image/" + typeimg);
            response.setHeader("Content-disposition",
                               "attachment; filename=orgchart." + typeimg
                              );

            ServletOutputStream servletOutputStream =
                response.getOutputStream();
            servletOutputStream.write(byteArray, 0, byteArray.length);
            servletOutputStream.write(byteArray, 0, byteArray.length);
            servletOutputStream.flush();
            servletOutputStream.close();
        }
        catch (Exception se)
        {
            se.printStackTrace();
        }
    }
}
